<?php
/**
 * 消息控制器
 */

declare (strict_types = 1);

namespace app\controller\home;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class Message extends BaseController
{
    /**
     * 收件箱
     */
    public function inbox()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            
            // 构建查询条件
            $where = [];
            $where[] = ['to_uid', '=', $userId];
            $where[] = ['delete_time', '=', 0];
            
            if (!empty($param['keywords'])) {
                $where[] = ['title', 'like', '%' . $param['keywords'] . '%'];
            }
            
            if (!empty($param['read'])) {
                if ($param['read'] == 1) {
                    $where[] = ['read_time', '=', 0];
                } else {
                    $where[] = ['read_time', '>', 0];
                }
            }
            
            if (!empty($param['types'])) {
                if ($param['types'] == 1) {
                    $where[] = ['from_uid', '=', 0]; // 系统消息
                } else {
                    $where[] = ['from_uid', '>', 0]; // 用户消息
                }
            }
            
            // 按发送时间检索
            if (!empty($param['range_time'])) {
                $rangeTime = explode('~', $param['range_time']);
                $startTime = strtotime(urldecode($rangeTime[0]));
                $endTime = strtotime(urldecode($rangeTime[1]));
                $where[] = ['send_time', 'between', [$startTime, $endTime]];
            }
            
            // 查询消息列表
            $list = Db::name('msg')
                ->where($where)
                ->page($page, $limit)
                ->order('send_time', 'desc')
                ->select()
                ->each(function($item) {
                    $item['send_time_format'] = date('Y-m-d H:i', $item['send_time']);
                    $item['read_time_format'] = $item['read_time'] ? date('Y-m-d H:i', $item['read_time']) : '';
                    
                    // 发件人信息
                    if ($item['from_uid'] > 0) {
                        $item['from_user'] = Db::name('admin')->where('id', $item['from_uid'])->value('name');
                    } else {
                        $item['from_user'] = '系统';
                    }
                    
                    return $item;
                });
            
            // 查询总数
            $count = Db::name('msg')
                ->where($where)
                ->count();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 发件箱
     */
    public function sendbox()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            
            // 构建查询条件
            $where = [];
            $where[] = ['from_uid', '=', $userId];
            $where[] = ['delete_time', '=', 0];
            $where[] = ['is_draft', '=', 1]; // 非草稿
            
            if (!empty($param['keywords'])) {
                $where[] = ['title', 'like', '%' . $param['keywords'] . '%'];
            }
            
            // 按发送时间检索
            if (!empty($param['range_time'])) {
                $rangeTime = explode('~', $param['range_time']);
                $startTime = strtotime(urldecode($rangeTime[0]));
                $endTime = strtotime(urldecode($rangeTime[1]));
                $where[] = ['send_time', 'between', [$startTime, $endTime]];
            }
            
            // 查询消息列表
            $list = Db::name('message')
                ->where($where)
                ->page($page, $limit)
                ->order('send_time', 'desc')
                ->select()
                ->each(function($item) {
                    $item['send_time_format'] = date('Y-m-d H:i', $item['send_time']);
                    
                    // 收件人信息
                    if (!empty($item['to_uid'])) {
                        if (strpos($item['to_uid'], ',') !== false) {
                            // 多个收件人
                            $uids = explode(',', trim($item['to_uid'], ','));
                            $users = Db::name('admin')->where('id', 'in', $uids)->column('name');
                            $item['to_users'] = implode(',', $users);
                        } else {
                            // 单个收件人
                            $item['to_users'] = Db::name('admin')->where('id', $item['to_uid'])->value('name');
                        }
                    } else {
                        $item['to_users'] = '';
                    }
                    
                    return $item;
                });
            
            // 查询总数
            $count = Db::name('message')
                ->where($where)
                ->count();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 星标信息
     */
    public function star()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            
            // 构建查询条件
            $where = [];
            $where[] = ['to_uid', '=', $userId];
            $where[] = ['delete_time', '=', 0];
            $where[] = ['is_star', '=', 1];
            
            if (!empty($param['keywords'])) {
                $where[] = ['title', 'like', '%' . $param['keywords'] . '%'];
            }
            
            if (!empty($param['read'])) {
                if ($param['read'] == 1) {
                    $where[] = ['read_time', '=', 0];
                } else {
                    $where[] = ['read_time', '>', 0];
                }
            }
            
            // 按发送时间检索
            if (!empty($param['range_time'])) {
                $rangeTime = explode('~', $param['range_time']);
                $startTime = strtotime(urldecode($rangeTime[0]));
                $endTime = strtotime(urldecode($rangeTime[1]));
                $where[] = ['send_time', 'between', [$startTime, $endTime]];
            }
            
            // 查询消息列表
            $list = Db::name('msg')
                ->where($where)
                ->page($page, $limit)
                ->order('send_time', 'desc')
                ->select()
                ->each(function($item) {
                    $item['send_time_format'] = date('Y-m-d H:i', $item['send_time']);
                    $item['read_time_format'] = $item['read_time'] ? date('Y-m-d H:i', $item['read_time']) : '';
                    
                    // 发件人信息
                    if ($item['from_uid'] > 0) {
                        $item['from_user'] = Db::name('admin')->where('id', $item['from_uid'])->value('name');
                    } else {
                        $item['from_user'] = '系统';
                    }
                    
                    return $item;
                });
            
            // 查询总数
            $count = Db::name('msg')
                ->where($where)
                ->count();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 草稿箱
     */
    public function draft()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            
            // 构建查询条件
            $where = [];
            $where[] = ['from_uid', '=', $userId];
            $where[] = ['delete_time', '=', 0];
            $where[] = ['is_draft', '=', 2]; // 草稿
            
            if (!empty($param['keywords'])) {
                $where[] = ['title', 'like', '%' . $param['keywords'] . '%'];
            }
            
            // 按发送时间检索
            if (!empty($param['range_time'])) {
                $rangeTime = explode('~', $param['range_time']);
                $startTime = strtotime(urldecode($rangeTime[0]));
                $endTime = strtotime(urldecode($rangeTime[1]));
                $where[] = ['send_time', 'between', [$startTime, $endTime]];
            }
            
            // 查询消息列表
            $list = Db::name('message')
                ->where($where)
                ->page($page, $limit)
                ->order('send_time', 'desc')
                ->select()
                ->each(function($item) {
                    $item['send_time_format'] = date('Y-m-d H:i', $item['send_time']);
                    return $item;
                });
            
            // 查询总数
            $count = Db::name('message')
                ->where($where)
                ->count();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 垃圾箱
     */
    public function rubbish()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            
            // 构建查询条件
            $where1 = [];
            $where1[] = ['from_uid', '=', $userId];
            $where1[] = ['delete_time', '>', 0];
            $where1[] = ['clear_time', '=', 0];
            
            $where2 = [];
            $where2[] = ['to_uid', '=', $userId];
            $where2[] = ['delete_time', '>', 0];
            $where2[] = ['clear_time', '=', 0];
            
            if (!empty($param['keywords'])) {
                $where1[] = ['title', 'like', '%' . $param['keywords'] . '%'];
                $where2[] = ['title', 'like', '%' . $param['keywords'] . '%'];
            }
            
            // 按发送/接收时间检索
            if (!empty($param['range_time'])) {
                $rangeTime = explode('~', $param['range_time']);
                $startTime = strtotime(urldecode($rangeTime[0]));
                $endTime = strtotime(urldecode($rangeTime[1]));
                $where1[] = ['send_time', 'between', [$startTime, $endTime]];
                $where2[] = ['send_time', 'between', [$startTime, $endTime]];
            }
            
            // 分别查询发件箱和收件箱的删除消息
            $sendList = Db::name('message')
                ->where($where1)
                ->field('id, title, from_uid, to_uid, send_time, delete_time, 1 as msg_type')
                ->select()
                ->toArray();
            
            $receiveList = Db::name('msg')
                ->where($where2)
                ->field('id, title, from_uid, to_uid, send_time, delete_time, 2 as msg_type')
                ->select()
                ->toArray();
            
            // 合并数组
            $list = array_merge($sendList, $receiveList);
            
            // 按删除时间排序
            usort($list, function($a, $b) {
                return $b['delete_time'] - $a['delete_time'];
            });
            
            // 分页处理
            $total = count($list);
            $list = array_slice($list, ($page - 1) * $limit, $limit);
            
            // 处理数据
            foreach ($list as &$item) {
                $item['send_time_format'] = date('Y-m-d H:i', $item['send_time']);
                $item['delete_time_format'] = date('Y-m-d H:i', $item['delete_time']);
                
                if ($item['msg_type'] == 1) {
                    // 发件箱消息
                    $item['msg_type_name'] = '发件';
                    if (!empty($item['to_uid'])) {
                        if (strpos($item['to_uid'], ',') !== false) {
                            // 多个收件人
                            $uids = explode(',', trim($item['to_uid'], ','));
                            $users = Db::name('admin')->where('id', 'in', $uids)->column('name');
                            $item['to_users'] = implode(',', $users);
                        } else {
                            // 单个收件人
                            $item['to_users'] = Db::name('admin')->where('id', $item['to_uid'])->value('name');
                        }
                    } else {
                        $item['to_users'] = '';
                    }
                } else {
                    // 收件箱消息
                    $item['msg_type_name'] = '收件';
                    if ($item['from_uid'] > 0) {
                        $item['from_user'] = Db::name('admin')->where('id', $item['from_uid'])->value('name');
                    } else {
                        $item['from_user'] = '系统';
                    }
                }
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $total
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 查看消息详情
     */
    public function view()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            
            if (empty($param['id'])) {
                return json(['code' => 400, 'msg' => '参数错误']);
            }
            
            if (empty($param['type'])) {
                return json(['code' => 400, 'msg' => '消息类型不能为空']);
            }
            
            if ($param['type'] == 1) {
                // 发件箱消息
                $message = Db::name('message')
                    ->where(['id' => $param['id'], 'from_uid' => $userId])
                    ->find();
                
                if (!$message) {
                    return json(['code' => 404, 'msg' => '消息不存在']);
                }
                
                $message['send_time_format'] = date('Y-m-d H:i', $message['send_time']);
                
                // 收件人信息
                if (!empty($message['to_uid'])) {
                    if (strpos($message['to_uid'], ',') !== false) {
                        // 多个收件人
                        $uids = explode(',', trim($message['to_uid'], ','));
                        $users = Db::name('admin')->where('id', 'in', $uids)->column('name');
                        $message['to_users'] = implode(',', $users);
                    } else {
                        // 单个收件人
                        $message['to_users'] = Db::name('admin')->where('id', $message['to_uid'])->value('name');
                    }
                } else {
                    $message['to_users'] = '';
                }
            } else {
                // 收件箱消息
                $message = Db::name('msg')
                    ->where(['id' => $param['id'], 'to_uid' => $userId])
                    ->find();
                
                if (!$message) {
                    return json(['code' => 404, 'msg' => '消息不存在']);
                }
                
                // 标记为已读
                if ($message['read_time'] == 0) {
                    Db::name('msg')
                        ->where('id', $param['id'])
                        ->update([
                            'read_time' => time(),
                            'update_time' => time()
                        ]);
                    $message['read_time'] = time();
                }
                
                $message['send_time_format'] = date('Y-m-d H:i', $message['send_time']);
                $message['read_time_format'] = $message['read_time'] ? date('Y-m-d H:i', $message['read_time']) : '';
                
                // 发件人信息
                if ($message['from_uid'] > 0) {
                    $message['from_user'] = Db::name('admin')->where('id', $message['from_uid'])->value('name');
                } else {
                    $message['from_user'] = '系统';
                }
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $message
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 发送消息
     */
    public function send()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            
            // 数据验证
            if (empty($param['title'])) {
                return json(['code' => 400, 'msg' => '消息标题不能为空']);
            }
            
            if (empty($param['content'])) {
                return json(['code' => 400, 'msg' => '消息内容不能为空']);
            }
            
            if (empty($param['to_uid'])) {
                return json(['code' => 400, 'msg' => '收件人不能为空']);
            }
            
            // 处理收件人
            $toUids = is_array($param['to_uid']) ? $param['to_uid'] : explode(',', $param['to_uid']);
            $toUids = array_filter($toUids); // 去除空值
            
            if (empty($toUids)) {
                return json(['code' => 400, 'msg' => '收件人不能为空']);
            }
            
            // 检查收件人是否存在
            $validUsers = Db::name('admin')
                ->where('id', 'in', $toUids)
                ->where('status', 1)
                ->column('id');
            
            $invalidUids = array_diff($toUids, $validUsers);
            if (!empty($invalidUids)) {
                return json(['code' => 400, 'msg' => '部分收件人不存在或已被禁用']);
            }
            
            $toUidStr = ',' . implode(',', $toUids) . ',';
            
            // 插入发件箱记录
            $messageData = [
                'title' => $param['title'],
                'content' => $param['content'],
                'from_uid' => $userId,
                'to_uid' => $toUidStr,
                'send_time' => time(),
                'is_draft' => 1, // 非草稿
                'create_time' => time(),
                'update_time' => time()
            ];
            
            $messageId = Db::name('message')->insertGetId($messageData);
            
            // 插入收件箱记录（每个收件人一条）
            foreach ($toUids as $toUid) {
                $msgData = [
                    'title' => $param['title'],
                    'content' => $param['content'],
                    'from_uid' => $userId,
                    'to_uid' => $toUid,
                    'send_time' => time(),
                    'create_time' => time(),
                    'update_time' => time()
                ];
                
                Db::name('msg')->insert($msgData);
            }
            
            return json(['code' => 0, 'msg' => '发送成功', 'data' => ['id' => $messageId]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '发送失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 保存草稿
     */
    public function save_draft()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            
            // 数据验证
            if (empty($param['title'])) {
                return json(['code' => 400, 'msg' => '消息标题不能为空']);
            }
            
            if (empty($param['content'])) {
                return json(['code' => 400, 'msg' => '消息内容不能为空']);
            }
            
            // 处理收件人
            $toUidStr = '';
            if (!empty($param['to_uid'])) {
                $toUids = is_array($param['to_uid']) ? $param['to_uid'] : explode(',', $param['to_uid']);
                $toUids = array_filter($toUids); // 去除空值
                if (!empty($toUids)) {
                    $toUidStr = ',' . implode(',', $toUids) . ',';
                }
            }
            
            $messageData = [
                'title' => $param['title'],
                'content' => $param['content'],
                'from_uid' => $userId,
                'to_uid' => $toUidStr,
                'send_time' => time(),
                'is_draft' => 2, // 草稿
                'create_time' => time(),
                'update_time' => time()
            ];
            
            if (!empty($param['id'])) {
                // 更新草稿
                $messageData['id'] = $param['id'];
                Db::name('message')->update($messageData);
                $messageId = $param['id'];
            } else {
                // 新建草稿
                $messageId = Db::name('message')->insertGetId($messageData);
            }
            
            return json(['code' => 0, 'msg' => '保存成功', 'data' => ['id' => $messageId]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '保存失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 标记星标消息
     */
    public function star_toggle()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            
            if (empty($param['id'])) {
                return json(['code' => 400, 'msg' => '参数错误']);
            }
            
            // 检查消息是否存在
            $msg = Db::name('msg')
                ->where(['id' => $param['id'], 'to_uid' => $userId])
                ->find();
            
            if (!$msg) {
                return json(['code' => 404, 'msg' => '消息不存在']);
            }
            
            // 切换星标状态
            $isStar = $msg['is_star'] == 1 ? 0 : 1;
            
            Db::name('msg')
                ->where('id', $param['id'])
                ->update([
                    'is_star' => $isStar,
                    'update_time' => time()
                ]);
            
            $msgType = $isStar == 1 ? '添加' : '取消';
            
            return json(['code' => 0, 'msg' => $msgType . '星标成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '操作失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除消息
     */
    public function delete()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            
            if (empty($param['id'])) {
                return json(['code' => 400, 'msg' => '参数错误']);
            }
            
            if (empty($param['type'])) {
                return json(['code' => 400, 'msg' => '消息类型不能为空']);
            }
            
            if ($param['type'] == 1) {
                // 删除发件箱消息
                $result = Db::name('message')
                    ->where(['id' => $param['id'], 'from_uid' => $userId])
                    ->update([
                        'delete_time' => time(),
                        'update_time' => time()
                    ]);
            } else {
                // 删除收件箱消息
                $result = Db::name('msg')
                    ->where(['id' => $param['id'], 'to_uid' => $userId])
                    ->update([
                        'delete_time' => time(),
                        'update_time' => time()
                    ]);
            }
            
            if ($result) {
                return json(['code' => 0, 'msg' => '删除成功']);
            } else {
                return json(['code' => 404, 'msg' => '消息不存在']);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 彻底删除消息
     */
    public function clear()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            
            if (empty($param['id'])) {
                return json(['code' => 400, 'msg' => '参数错误']);
            }
            
            if (empty($param['type'])) {
                return json(['code' => 400, 'msg' => '消息类型不能为空']);
            }
            
            if ($param['type'] == 1) {
                // 彻底删除发件箱消息
                $result = Db::name('message')
                    ->where(['id' => $param['id'], 'from_uid' => $userId])
                    ->where('delete_time', '>', 0)
                    ->update([
                        'clear_time' => time(),
                        'update_time' => time()
                    ]);
            } else {
                // 彻底删除收件箱消息
                $result = Db::name('msg')
                    ->where(['id' => $param['id'], 'to_uid' => $userId])
                    ->where('delete_time', '>', 0)
                    ->update([
                        'clear_time' => time(),
                        'update_time' => time()
                    ]);
            }
            
            if ($result) {
                return json(['code' => 0, 'msg' => '彻底删除成功']);
            } else {
                return json(['code' => 404, 'msg' => '消息不存在或未删除']);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取各类消息统计
     */
    public function count()
    {
        try {
            $userId = $this->getUserId();
            
            // 发件箱草稿数量
            $sendboxCount = Db::name('message')
                ->where([
                    ['from_uid', '=', $userId],
                    ['is_draft', '=', 1],
                    ['delete_time', '=', 0]
                ])
                ->count();
            
            // 收件箱未读消息数量
            $inboxCount = Db::name('msg')
                ->where([
                    ['to_uid', '=', $userId],
                    ['delete_time', '=', 0],
                    ['read_time', '=', 0]
                ])
                ->count();
            
            // 星标消息数量
            $starCount = Db::name('msg')
                ->where([
                    ['to_uid', '=', $userId],
                    ['delete_time', '=', 0],
                    ['is_star', '=', 1]
                ])
                ->count();
            
            // 草稿箱数量
            $draftCount = Db::name('message')
                ->where([
                    ['from_uid', '=', $userId],
                    ['is_draft', '=', 2],
                    ['delete_time', '=', 0]
                ])
                ->count();
            
            // 垃圾箱数量
            $sendRubbishCount = Db::name('message')
                ->where([
                    ['from_uid', '=', $userId],
                    ['delete_time', '>', 0],
                    ['clear_time', '=', 0]
                ])
                ->count();
            
            $receiveRubbishCount = Db::name('msg')
                ->where([
                    ['to_uid', '=', $userId],
                    ['delete_time', '>', 0],
                    ['clear_time', '=', 0]
                ])
                ->count();
            
            $rubbishCount = $sendRubbishCount + $receiveRubbishCount;
            
            $count = [
                'sendbox' => $sendboxCount,
                'inbox' => $inboxCount,
                'star' => $starCount,
                'draft' => $draftCount,
                'rubbish' => $rubbishCount
            ];
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
}